(function ($) {
    $.fn.extend({
        "svVideo": function (options) {

            // 默认参数
            var defaluts = {
                url: "",
                videoId: "",
                quality: 1
            };

            var objs = [];

            // 遍历所有的符合的dom
            this.each(function () {
                // 获取当前dom 的 jQuery对象
                var _canvas = this;
                var $this = $(this);

                // 根据参数来设置 dom的样式
                // $this.css({
                // backgroundColor: option.background,
                // color: option.foreground
                // });
                var option = $.extend({}, defaluts, options);

                var _lastFrameId = -1;

                var _context = this.getContext('2d');
                var _cvsWidth = $this.width();
                var _cvsHeight = $this.height();

                var _socket = null;
                var _recvFalg = 1;
                var _timeLoad = null;
                var _isOpen = false;
                var _lastMsg = "";
                var _lastColor = null;

                function _startSend() {
                    _stopSend();
                    _recvFalg = 1;
                    _timeLoad = setInterval(function () {
                        _sendMsg();
                    }, 1000 / 15);
                }

                function _stopSend() {
                    _recvFalg = 0;
                    if (_timeLoad) clearInterval(_timeLoad);
                }

                function _showPaint(msg, color) {

                    if (msg) {
                        _lastMsg = msg;
                        _lastColor = color ? color : '#0000FF';

                        _context.fillStyle = 'black';
                        _context.fillRect(0, 0, _cvsWidth, _cvsHeight);
                        _context.fillStyle = _lastColor;
                        _context.textAlign = "center";
                        _context.font = "bold 12px '宋体'";
                        _context.fillText(msg, _cvsWidth / 2, _cvsHeight / 2);
                    } else {
                        _lastMsg = null;
                        _lastColor = null;
                    }
                }

                function _preView(isPreView) {
                    var q = {
                        videoId: option.videoId,
                        isPreView: isPreView
                    };
                    var json = JSON.stringify(q);
                    console.log(json);
                    _socket.send(json);
                    console.log("发送成功")
                }

                function _sendMsg(commandCode, dwPTZCommand, dwStop, isPreview, recordVideo, searchType, playBackFileName) {
                    try {
                        _recvFalg = 0;
                        var q = {
                            videoId: option.videoId,
                            commandCode: commandCode,
                            // Width: _cvsWidth,
                            // height: _cvsHeight,
                            // Quality: option.quality,
                            // LastFrameId: _lastFrameId,
                            dwPTZCommand: dwPTZCommand,
                            dwSpeed: $("#ptzspeed").val(),
                            isPreView: isPreview,
                            recordVideo: recordVideo,
                            dwStop: dwStop,
                            searchType: searchType,
                            playBackFileName: playBackFileName,
                            struBeginTime: $("#startTime").val(),
                            struEndTime: $("#endTime").val()
                        };
                        _socket.send(JSON.stringify(q));
                        console.log("发送成功" + commandCode)
                    } catch (ex) {
                        console.log(ex)
                        _close();
                    }
                }

                function onOpen(event) {
                    _isOpen = true;
                    _recvFalg = 1;
                    _showPaint("已连接到服务器...");
                    // _startSend();
                }

                function onClose(event) {
                    _stopSend();
                    if (_isOpen) {
                        _showPaint("连接已断开！", "#FF0000");
                    }
                }

                function onError(event) {
                    // 是否连接成功状态
                    if (_socket.readyState != 1) {
                        _stopSend();
                    }
                    _showPaint("连接服务器失败！");
                }


                function onMessage(event) {
                    _recvFalg = 1;
                    var r = JSON.parse(event.data);
                    console.log(r.FrameData);
                    if (r.State == 2) {
                        var isCapture = confirm('你刚才截图了,您要不要截图文件？');
                        if (isCapture) {
                            downLoadImg(r.FrameData);
                        }
                        $("#handMsg").prepend( getTime()+" : "+r.StateMsg  + "<br/>")
                        return;
                    }

                    if (r.State == 4) {
                        if (r.FrameId == 1) {
                            $("#video").val(r.FrameData);
                        } else {
                            var isRecord = confirm('你刚才录像了,您要不要录像文件？');
                            if (isRecord) {
                                var videoPath = $("#video").val();
                                downLoadVideo(videoPath);
                            }
                        }
                        $("#handMsg").prepend(getTime()+" : "+r.StateMsg  + "<br/>")
                        return;
                    }

                    if (r.State == 3) {
                        _close();
                        _showPaint(r.StateMsg, "#FF0000");
                        return;
                    }

                    console.log(CheckIsNullOrEmpty(r.StateMsg) + "====" + r.StateMsg);
                    if (r.State == 1 && r.FrameId == 1) {
                        if (CheckIsNullOrEmpty(r.StateMsg)) {
                            $("#handMsg").prepend(getTime()+" : "+r.StateMsg  + "<br/>");
                        }
                    }


                    if (r.State == 5 && r.FrameId == 1) {
                        var frameData = JSON.parse(r.FrameData);
                        console.log(frameData);
                        $.each(frameData, function (i, o) {
                            var fileName = o[0];
                            console.log("fileName" + fileName)
                            var playBack = "<tr> <td>" + fileName + "</td><td>" + o[1] + "</td><td>" + o[2] + "</td><td>";
                            playBack += '<a href="#" onclick="playBackSart(' + "'" + fileName + "'" + ')" >' + "play </a> </td></tr>";
                            playBack += '<a href="#" onclick="playBackStop(' + "'" + fileName + "'" + ')" >' + "stop </a> </td></tr>";
                            $(".playBackItem").html(playBack);
                        });
                        $("#handMsg").html(getTime()+" : "+r.StateMsg  + "<br/>")
                        return;
                    }
                    _lastFrameId = r.FrameId;

                    if (r.FrameData) {
                        var imgObj = new Image();
                        imgObj.src = r.FrameData;
                        console.log(imgObj.src);
                        imgObj.onload = function () {
                            _context.drawImage(this, 0, 0, _cvsWidth, _cvsHeight);
                        }
                    }
                }

                function _open(url) {
                    if (_socket) {
                        var s = _socket.readyState;
                        // 正在连接或连接成功
                        if (s == 0 || s == 1) return;
                    }
                    if (url) option.url = url;
                    try {
                        _showPaint("连接服务器...");
                        _socket = new WebSocket(url);
                        _socket.onopen = onOpen;
                        _socket.onclose = onClose;
                        _socket.onerror = onError;
                        _socket.onmessage = onMessage;
                    } catch (ex) {
                        _showPaint("连接服务器出错！ - " + ex.message, "#FF0000");
                    }
                }

                function _close() {
                    if (_socket) {
                        var s = _socket.readyState;
                        // 正在连接或连接成功
                        if (s == 0 || s == 1) {
                            _socket.close();
                        }
                        _socket = null;

                        _isOpen = false;
                        _showPaint("断开连接");
                    }
                }

                $this.open = _open;
                $this.close = _close;
                $this.send = _sendMsg;
                $this.preView = _preView;
                $this.setOption = function (newOpt) {
                    $.extend(option, newOpt);
                }

                $this.resize = function (w, h) {
                    if (w && _canvas.width != w) _canvas.width = w;
                    if (h && _canvas.height != h) _canvas.height = h;

                    _cvsWidth = $this.width();
                    _cvsHeight = $this.height();

                    if (_lastMsg) _showPaint(_lastMsg, _lastColor);
                };

                _showPaint("");

                objs.push($this);
            });
            return objs;
        }
    });
})(window.jQuery);
